const Router = require("koa-router");
const router = new Router();
let user = [
  {
    username: "17752644860",
    password: "hcq200506",
    role: "admin",
    img: "https://tse1-mm.cn.bing.net/th/id/OIP-C.VnqbqHI999-VVVkUOWBcMwAAAA?w=190&h=190&c=7&r=0&o=5&dpr=1.5&pid=1.7",
  },
  {
    username: "admin",
    password: "admin",
    role: "user",
    img: "https://tse4-mm.cn.bing.net/th/id/OIP-C.8NKbqA2JWQif-dYyY0s-xAAAAA?w=197&h=197&c=7&r=0&o=5&dpr=1.5&pid=1.7",
  },
  {
    username: "user",
    password: "user",
    role: "user",
    img: "https://tse2-mm.cn.bing.net/th/id/OIP-C.vZFNoKcwouKDRXky39DlKwAAAA?w=165&h=180&c=7&r=0&o=5&dpr=1.5&pid=1.7",
  },
];
let codetype = null;
let code1 = null;
/*
 接口：        功能:        请求方式:     参数":
 login        登录         post               { username, password }
 register     注册         post               { username, password }
 code         获取验证码    get
 tabs         tabs切换     get
 git           商城页面宫格 get 
banner        轮播图       get
date          医生mock模拟        get
*/

router.post("/login", async (ctx, body) => {
  let { username, password, code } = ctx.request.body;
  let status = user.find((item) => item.username === username);
  if (!status) {
    return (ctx.body = {
      code: 400,
      msg: "用户名不存在",
    });
  }
  if (!code) {
    let res = user.find(
      (item) => item.username === username && item.password === password
    );
    if (res) {
      ctx.body = {
        code: 200,
        msg: "登录成功",
        data: res,
      };
    } else {
      ctx.body = {
        code: 400,
        msg: "登录失败",
      };
    }
  } else {
    if (code == codetype || code == code1) {
      return (ctx.body = {
        code: 200,
        msg: "登录成功",
      });
    } else {
      ctx.body = {
        code: 400,
        msg: "验证码错误",
      };
    }
  }
});
router.post("/register", async (ctx, body) => {
  let { username, password } = ctx.request.body;
  let res = user.find((item) => item.username === username);
  if (res) {
    ctx.body = {
      code: 400,
      msg: "用户名已存在",
    };
  } else {
    user.push({
      username,
      password,
      role: "role",
      img: "",
    });
    ctx.body = {
      code: 200,
      msg: "注册成功",
    };
  }
});
router.get("/code", async (ctx, body) => {
  code1 = Math.random().toString(36).substr(2, 4).toUpperCase(); //生成随机验证码
  codetype = Math.random().toString().slice(2, 6);
  ctx.body = {
    code: 200,
    msg: "获取验证码成功",
    data: [codetype, code1],
  };
});

module.exports = router;
